package com.jeasyuicn.rbac.controller;

import com.jeasyuicn.rbac.model.dao.UserDao;
import com.jeasyuicn.rbac.model.entity.User;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * <p>****************************************************************************</p>
 * <p><b>Copyright © 2010-2017 soho team All Rights Reserved<b></p>
 * <ul style="margin:15px;">
 * <li>Description : com.jeasyuicn.rbac.controller</li>
 * <li>Version     : 1.0</li>
 * <li>Creation    : 2017年10月23日</li>
 * <li>@author      : ____′↘夏悸 <wmails@126.com></li>
 * </ul>
 * <p>****************************************************************************</p>
 */
@Controller
@RequestMapping("/")
public class AppController {

    @Autowired
    private UserDao userDao;

    @RequestMapping
    public String index(@SessionAttribute(value = "user", required = false) User user) {
        if (user == null) {
            //此处表示未登录
            return "login";
        }
        //已登录
        return "index";
    }

    @PostMapping("/login")
    public String login(@RequestParam String account, @RequestParam String password, HttpSession session, RedirectAttributes rda) {
        User user = userDao.findFirstByAccount(account);
        //判断账号是否可用
        if (user != null && user.getEnable()) {
            //判断密码是否匹配
            if (user.getPassword().equals(DigestUtils.md5Hex(password))) {
                session.setAttribute("user", user);
            } else {
                rda.addFlashAttribute("error", "账号和密码不匹配！");
            }
        } else {
            rda.addFlashAttribute("error", "账号不可用！");
        }
        return "redirect:/";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/";
    }
}
